package com.atguigu.state;

import com.atguigu.bean.WaterSensor;
import com.atguigu.functions.MapFunction2Impl;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;


/**
 * @author gmd
 * @desc 状态后端。实时监测水位值的变化并输出警告信息。
 * @since 2024-12-01 11:47:28
 */
public class StateBackend {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 1. 使用 hashmap状态后端
        HashMapStateBackend hashMapStateBackend = new HashMapStateBackend();
        env.setStateBackend(hashMapStateBackend);
        // 2. 使用 rocksdb状态后端
        EmbeddedRocksDBStateBackend embeddedRocksDBStateBackend = new EmbeddedRocksDBStateBackend();
        env.setStateBackend(embeddedRocksDBStateBackend);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("127.0.0.1", 7777)
                .map(new MapFunction2Impl())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((element, ts) -> element.getTs() * 1000L)
                );

        sensorDS.keyBy(r -> r.getId())
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            // 值状态
                            ValueState<Integer> lastVcState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                super.open(parameters);
                                lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Types.INT));
                            }

                            @Override
                            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {


                                int lastVc = lastVcState.value() == null ? 0 : lastVcState.value();
                                Integer vc = value.getVc();
                                if (Math.abs(vc - lastVc) > 10) {
                                    out.collect("传感器=" + value.getId() + "==>当前水位值=" + vc + "，与上一条水位值=" + lastVc + "，相差超过10！");
                                }
                                lastVcState.update(vc);
                            }
                        }
                ).print();

        env.execute();
    }

    /*
     * 状态后端配置
     * =====================
     *
     * 状态后端是Flink用于管理状态的组件，负责存储和管理应用程序的状态。
     *
     * 1. 状态后端的作用
     * ----------------
     *
     *   - 负责管理本地状态
     *   - 提供了两种状态后端实现：HashMapStateBackend和EmbeddedRocksDBStateBackend
     *
     * 2. 状态后端的实现
     * -----------------
     *
     *   - HashMapStateBackend：存储状态在TaskManager的JVM堆内存中，读写快，但存储空间有限
     *   - EmbeddedRocksDBStateBackend：存储状态在TaskManager所在节点的RocksDB数据库中，存储空间大，但读写相对慢
     *
     * 3. 配置方式
     * -------------
     *
     *   - 配置文件：默认值在flink-conf.yaml中配置
     *   - 代码中指定：可以在代码中直接指定状态后端
     *   - 提交参数指定：可以通过命令行参数指定状态后端
     *     例如：flink run-application -t yarn-application -p 3 -Dstate.backend.type=rocksdb -c 全类名 jar包
     */

}
